import 'dart:async';

import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hi_common/hi_common.dart';

import 'base_text_form_field.dart';

class PhoneCodeFormField extends StatefulWidget {
  final String codeType;
  final String phone;
  final ValueChanged<String> onChanged;

  const PhoneCodeFormField({
    Key key,
    @required this.codeType,
    @required this.phone,
    this.onChanged,
  }) : super(key: key);

  @override
  _PhoneCodeFormFieldState createState() => _PhoneCodeFormFieldState();
}

class _PhoneCodeFormFieldState extends State<PhoneCodeFormField> {
  @override
  Widget build(BuildContext context) {
    return BaseTextFormField(
      hintText: '请输入短信验证码',
      textAlign: TextAlign.start,
      onChanged: widget.onChanged,
      keyboardType: TextInputType.number,
      inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
      suffix: CodeBtn(
        phone: widget.phone,
        codeType: widget.codeType,
      ),
      horizontalPadding: 0,
    );
  }
}

enum CodeBtnStatus {
  normal,
  loading,
  success,
  failed,
}

class CodeType {
  static final String regist = 'add_store';
  static final String updatePassword = 'update_password';
  static final String loginVerifycode = 'login_verifycode';
}

class CodeBtn extends StatefulWidget {
  final String phone;
  final String codeType;

  @override
  _CodeBtnState createState() => _CodeBtnState();

  const CodeBtn({this.phone = '', this.codeType, Key key}) : super(key: key);
}

class _CodeBtnState extends State<CodeBtn> {
  CodeBtnStatus _status = CodeBtnStatus.normal;
  int _time = 60;
  Timer _timer;

  _getPhoneCode() async {
    if (widget.phone != null && RegUtil.testPhone(widget.phone)) {
      setState(() {
        _status = CodeBtnStatus.loading;
      });
      var res = await api.getValidateCode({
        'phone': widget.phone,
        'codeType': widget.codeType,
      });
      if (res.successful()) {
        _startTimer();
        setState(() {
          _status = CodeBtnStatus.success;
        });
      } else {
        setState(() {
          _status = CodeBtnStatus.failed;
        });
        toast(res.msg);
      }
    } else {
      toast('请输入正确的手机号');
    }
  }

  _startTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _time--;
      });

      if (_time == 1) {
        setState(() {
          _status = CodeBtnStatus.normal;
          _time = 60;
          _timer.cancel();
          _timer = null;
        });
      }
    });
  }

  void _onTap() async {
    switch (_status) {
      case CodeBtnStatus.normal:
        _getPhoneCode();
        break;
      case CodeBtnStatus.failed:
        _getPhoneCode();
        break;
      case CodeBtnStatus.loading:
        break;
      case CodeBtnStatus.success:
        break;
    }
  }

  buildBtn() {
    var textStyle = TextStyleConstant().blue_28;

    switch (_status) {
      case CodeBtnStatus.normal:
        return Text(
          '获取验证码',
          style: textStyle,
        );
      case CodeBtnStatus.failed:
        return Text(
          '重新获取',
          style: textStyle,
        );
      case CodeBtnStatus.loading:
        return CupertinoActivityIndicator();
      case CodeBtnStatus.success:
        return Text(
          '${_time}s',
          style: textStyle,
        );
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _onTap,
      behavior: HitTestBehavior.translucent,
      child: Container(
        width: 171.w,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
            color: ColorConstant.e6e6,
            width: 1.px,
          )),
        ),
        child: buildBtn(),
      ),
    );
  }
}
